<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>在线翻译工具</title>
    <style>
        body {
            font-family: sans-serif;
            padding: 20px;
        }
        label, select, textarea, button {
            display: block;
            margin-top: 10px;
            width: 100%;
        }
        textarea {
            height: 100px;
        }
        #result {
            margin-top: 20px;
            padding: 10px;
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>

<h2>多语言翻译</h2>

<label for="from_lang">源语言</label>
<select id="from_lang"></select>

<label for="to_lang">目标语言</label>
<select id="to_lang"></select>

<label for="text">输入文本</label>
<textarea id="text"></textarea>

<button onclick="translateText()">翻译</button>

<div id="result"><strong>翻译结果：</strong> <span id="output"></span></div>

<script>
    async function loadLanguages() {
        const res = await fetch('/languages');
        const langs = await res.json();
        const fromSelect = document.getElementById('from_lang');
        const toSelect = document.getElementById('to_lang');

        langs.forEach(lang => {
            const option1 = document.createElement('option');
            option1.value = lang.code;
            option1.text = lang.name;
            fromSelect.appendChild(option1);

            const option2 = document.createElement('option');
            option2.value = lang.code;
            option2.text = lang.name;
            toSelect.appendChild(option2);
        });

        fromSelect.value = 'cn';
        toSelect.value = 'en';
    }

    async function translateText() {
        const from = document.getElementById('from_lang').value;
        const to = document.getElementById('to_lang').value;
        const text = document.getElementById('text').value;

        const response = await fetch('/translate', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({from_lang: from, to_lang: to, text})
        });

        if (response.ok) {
            const result = await response.text();
            document.getElementById('output').innerText = result;
        } else {
            const error = await response.text();
            document.getElementById('output').innerText = '错误: ' + error;
        }
    }

    loadLanguages();
</script>

</body>
</html>
